package com.zdw.demo.config.international;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

/**
 * 国际化/多语言(i18n)工具类
 * 注意:请求头中,需要带上国际化/多语言标识Accept-Language
 */
@Component
public class InternationalUtils {

    private static MessageSource messageSource;

    public InternationalUtils(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    /**
     * 获取国际化/多语言的实际返回值
     * 注意:请求头中,需要带上国际化/多语言标识Accept-Language
     *
     * @param key
     * @return
     */
    public static String getInternational(String key) {
        try {
            System.out.println("国际化/多语言messageSource:" + messageSource.toString());
            return messageSource.getMessage(
                    key,
                    null,
                    LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return key;
        }
    }

}
